import React, { useState, useContext, createContext } from "react";
import PropTypes from "prop-types";

const GlobalContext = createContext();

export const GlobalProvider = ({ children }) => {
  // 是否已登录
  const [isAuthenticated, setIsAuthenticated] = useState(
    localStorage.getItem("isAuthenticated") === "true"
  );
  // 已登录用户信息
  const [user, setUser] = useState(
    JSON.parse(localStorage.getItem("user") || "null")
  );
  // 当前问题
  const [question, setQuestion] = useState("");
  // 当前对话内容
  const [chatContent, setChatContent] = useState("");

  const login = (userData) => {
    console.log("userData:", userData);
    localStorage.setItem("isAuthenticated", "true");
    localStorage.setItem("user", JSON.stringify(userData));
    // 修改这里，直接存储 token 字符串，不要用 JSON.stringify
    localStorage.setItem("token", userData.token);
    setIsAuthenticated(true);
    setUser(userData);
  };
  const logout = () => {
    localStorage.removeItem("isAuthenticated");
    localStorage.removeItem("user");
    localStorage.removeItem("token");
    setIsAuthenticated(false);
    setUser(null);
  };

  // 更新用户信息
  const updateUserInfo = (newUserData) => {
    localStorage.setItem("user", JSON.stringify(newUserData));
    setUser(newUserData);
  };

  return (
    <GlobalContext.Provider
      value={{
        isAuthenticated,
        user,
        login,
        logout,
        chatContent,
        setChatContent,
        question,
        setQuestion,
        updateUserInfo,
      }}
    >
      {children}
    </GlobalContext.Provider>
  );
};

GlobalProvider.propTypes = {
  children: PropTypes.node.isRequired,
};

export const useGlobalContext = () => {
  const context = useContext(GlobalContext);
  if (!context) {
    throw new Error("useGlobalContext must be used within an AuthProvider");
  }
  return context;
};
